package com.example.furniture.service.impl;

import com.example.furniture.entity.Furniture;
import com.example.furniture.mapper.FurnitureMapper;
import com.example.furniture.service.FurnitureService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.List;

/**
 * 家具服务实现类
 * 提供家具相关的业务逻辑处理
 * 
 * @author 家具商城系统
 * @version 1.0
 * @since 2024-01-01
 */
@Service
@Transactional
public class FurnitureServiceImpl implements FurnitureService {

    private static final Logger logger = LoggerFactory.getLogger(FurnitureServiceImpl.class);
    private final FurnitureMapper furnitureMapper;

    /**
     * 构造函数，注入家具数据访问层
     * 
     * @param furnitureMapper 家具数据访问层实例
     */
    public FurnitureServiceImpl(FurnitureMapper furnitureMapper) {
        this.furnitureMapper = furnitureMapper;
    }

    /**
     * 根据ID获取家具信息
     * 
     * @param id 家具ID
     * @return 家具信息，如果不存在返回null
     */
    @Override
    public Furniture getById(Long id) {
        logger.debug("根据ID获取家具信息: {}", id);
        try {
            Furniture furniture = furnitureMapper.selectById(id);
            if (furniture != null) {
                logger.debug("成功获取家具信息: {}", furniture.getName());
            } else {
                logger.debug("家具不存在: {}", id);
            }
            return furniture;
        } catch (Exception e) {
            logger.error("获取家具信息失败，ID: {}", id, e);
            throw new RuntimeException("获取家具信息失败", e);
        }
    }

    /**
     * 获取所有家具列表
     * 
     * @return 家具列表
     */
    @Override
    public List<Furniture> listAll() {
        logger.debug("获取所有家具列表");
        try {
            List<Furniture> furniture = furnitureMapper.selectAll();
            logger.debug("成功获取家具列表，共{}条记录", furniture.size());
            return furniture;
        } catch (Exception e) {
            logger.error("获取家具列表失败", e);
            throw new RuntimeException("获取家具列表失败", e);
        }
    }

    /**
     * 创建新家具
     * 
     * @param furniture 家具信息
     * @return 创建的家具信息（包含生成的ID）
     */
    @Override
    public Furniture create(Furniture furniture) {
        logger.debug("创建新家具: {}", furniture.getName());
        try {
            // 验证家具信息
            validateFurniture(furniture);
            
            furnitureMapper.insert(furniture);
            logger.info("家具创建成功，ID: {}, 名称: {}", furniture.getId(), furniture.getName());
            return furniture;
        } catch (Exception e) {
            logger.error("创建家具失败: {}", furniture.getName(), e);
            throw new RuntimeException("创建家具失败", e);
        }
    }

    /**
     * 更新家具信息
     * 
     * @param id 家具ID
     * @param furniture 更新的家具信息
     * @return 更新后的家具信息
     */
    @Override
    public Furniture update(Long id, Furniture furniture) {
        logger.debug("更新家具信息，ID: {}", id);
        try {
            // 检查家具是否存在
            Furniture existingFurniture = furnitureMapper.selectById(id);
            if (existingFurniture == null) {
                logger.warn("家具不存在，无法更新，ID: {}", id);
                throw new RuntimeException("家具不存在");
            }
            
            // 验证家具信息
            validateFurniture(furniture);
            
            furniture.setId(id);
            furnitureMapper.update(furniture);
            Furniture updatedFurniture = furnitureMapper.selectById(id);
            logger.info("家具更新成功，ID: {}, 名称: {}", id, updatedFurniture.getName());
            return updatedFurniture;
        } catch (Exception e) {
            logger.error("更新家具失败，ID: {}", id, e);
            throw new RuntimeException("更新家具失败", e);
        }
    }

    /**
     * 删除家具
     * 
     * @param id 家具ID
     */
    @Override
    public void delete(Long id) {
        logger.debug("删除家具，ID: {}", id);
        try {
            // 检查家具是否存在
            Furniture existingFurniture = furnitureMapper.selectById(id);
            if (existingFurniture == null) {
                logger.warn("家具不存在，无法删除，ID: {}", id);
                throw new RuntimeException("家具不存在");
            }
            
            furnitureMapper.deleteById(id);
            logger.info("家具删除成功，ID: {}", id);
        } catch (Exception e) {
            logger.error("删除家具失败，ID: {}", id, e);
            throw new RuntimeException("删除家具失败", e);
        }
    }

    /**
     * 验证家具信息
     * 
     * @param furniture 家具信息
     */
    private void validateFurniture(Furniture furniture) {
        if (furniture.getName() == null || furniture.getName().trim().isEmpty()) {
            throw new RuntimeException("家具名称不能为空");
        }
        
        if (furniture.getPrice() == null || furniture.getPrice().compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("家具价格必须大于等于0");
        }
        
        if (furniture.getStock() == null || furniture.getStock() < 0) {
            throw new RuntimeException("库存数量必须大于等于0");
        }
        
        if (furniture.getCategoryId() == null) {
            throw new RuntimeException("必须选择家具分类");
        }
        
        logger.debug("家具信息验证通过: {}", furniture.getName());
    }
}


